<template>
  <div>
    <div ref="body">
      <table border="1">
        <tr>
          <td>asdf</td>
          <td style="color: red; font-size: 28px">asdf</td>
          <td>asdf</td>
          <td>
            <img
              ref="images"
              alt="Vue logo"
              src=""
            />
          </td>
        </tr>
      </table>
    </div>

    <img ref="toImg" alt="html2canvas" src="" />
  </div>
</template>

<script>
import html2canvas from "html2canvas";
export default {
  mounted() {
    // 生成快照
    const convertToImage = (container, options = {}) => {
      // 设置放大倍数
      const scale = window.devicePixelRatio;

      // 传入节点原始宽高
      // const _width = container.offsetWidth;
      // const _height = container.offsetHeight;

      // let { width, height } = options;
      // width = width || _width;
      // height = height || _height;

      // html2canvas配置项
      const ops = {
        scale,
        // width,
        // height,
        useCORS: true,
        allowTaint: false,
        ...options,
      };

      return html2canvas(container, ops).then((canvas) => {
        // 返回图片的二进制数据
        return canvas.toDataURL("image/png");
      });
    };

    // 调用函数，取到截图的二进制数据，对图片进行处理（保存本地、展示等）
    convertToImage(this.$refs.body).then((imgBlobData) => {
      console.log(imgBlobData);
      this.$refs.toImg.src = imgBlobData;
    });
  },
};
</script>